
#include <stdint.h>
#include "BitDefine.h"
#include "Contract.h"
#include "BSP.h"
#include "Driver.h"
#include "CH455I2C.h"
#include "Indecator.h"

#define BACKLIGHT_ALL		0xFFFF



static Indecator_T backlightIndecator = {
	.obj = {
		.objId = BACKLIGHT_ALL,
		.action = BSP_KeyboardBacklight_Set,
	},
};
		

void KeyBoardBacklight_Init(uint8_t mode){
	IndecatorSetting_T lightPermanent;
	
	lightPermanent.duration = 0;

	if(mode){
		lightPermanent.states[State_On].state = 0xFFFF;
		lightPermanent.states[State_On].time = 0xFFFF;
		lightPermanent.states[State_Off].state = 0xFFFF;
		lightPermanent.states[State_Off].time = 0;
		lightPermanent.current = State_On;
	}
	else{
		lightPermanent.states[State_On].state = 0xFFFF;
		lightPermanent.states[State_On].time = 0;
		lightPermanent.states[State_Off].state = 0x0000;
		lightPermanent.states[State_Off].time = 0xFFFF;
		lightPermanent.current = State_Off;
	}

	Indecator_Init();
	Indecator_Set(&backlightIndecator, Setting_Permanent, &lightPermanent, 0);
	Indecator_Register(&backlightIndecator);
	
}

//	static inline int KeyValueToLight(uint8_t value){
//		static const uint8_t valueToLight[12] = {
//			[0] = 9, [1] = 5, [2] = 4, [3] = 3,
//			[4] = 2, [5] = 1, [6] = 0, [7] = 11,
//			[8] = 12, [9] = 13, [0x0A] = 8, [0x0B] = 10,
//		};
//			
//		if(value > 0x0B){
//			return -1;
//		}
//		return valueToLight[value];
//	}

void KeyBoardBacklight_Pulse(uint8_t value, uint32_t time){
	IndecatorSetting_T lightTemp;
	uint32_t t = time / 10;
	
	if(t == 0){
		return;
	}
	uint8_t pos = BSP_Keyboard_ValToMap(value);
	uint32_t state = BACKLIGHT_ALL;
	
	state &= ~ Bit(pos);
	
	lightTemp.states[State_On].state = state;
	lightTemp.states[State_On].time = t;
	lightTemp.states[State_Off].state = 0xFFFF;
	lightTemp.states[State_Off].time = 500;
	lightTemp.current = State_On;
	lightTemp.duration = t + 500;
	
	Indecator_Set(&backlightIndecator, Setting_Temp, 0, &lightTemp);
}

void KeyBoardBacklight_Flash(uint8_t count, uint32_t onMs, uint32_t offMs, uint8_t state){
	IndecatorSetting_T lightTemp;
	uint32_t dulation;
	
	if(onMs == 0 && offMs == 0){
		return;
	}	
	
	lightTemp.states[State_On].state = 0xFFFF;
	lightTemp.states[State_On].time = onMs / 10;
	lightTemp.states[State_Off].state = 0;
	lightTemp.states[State_Off].time = offMs / 10;
	lightTemp.current = state ? State_On : State_Off;
	lightTemp.duration = (onMs/10 + offMs/10)*count;
	
	Indecator_Set(&backlightIndecator, Setting_Temp, 0, &lightTemp);
}


void KeyBoardBacklight_Permanent(void){
	Indecator_Set(&backlightIndecator, Setting_Permanent, 0, 0);
}


